﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml;

namespace MyWp7Brand
{
    public class RssClient
    {
        private readonly string _rssUrl;
        private object _control;

        public delegate void ItemsReceivedDelegate(RssClient client, IList<FeedItem> items, Object control);
        public event ItemsReceivedDelegate ItemsReceived;

        public RssClient(string rssUrl,object control)
        {
            _rssUrl = rssUrl;
            _control = control;
        }

        public void LoadItems()
        {
            var request = (HttpWebRequest)WebRequest.Create(_rssUrl);
            var result = (IAsyncResult)request.BeginGetResponse(ResponseCallback, request);
        }

        void ResponseCallback(IAsyncResult result)
        {
            var request = (HttpWebRequest)result.AsyncState;
            
            System.Net.WebResponse response;
            try
            {
                response = request.EndGetResponse(result);
            }
            catch (Exception)
            {
                if (ItemsReceived != null)
                    ItemsReceived(this, null, _control);
                return; }

            var stream = response.GetResponseStream();
            var reader = XmlReader.Create(stream);
            var items = new List<FeedItem>(50);

            FeedItem item = null;
            var pointerMoved = false;

            while (!reader.EOF)
            {
                if (pointerMoved)
                {
                    pointerMoved = false;
                }
                else
                {
                    if (!reader.Read())
                        break;
                }

                var nodeName = reader.Name;
                var nodeType = reader.NodeType;

                if (nodeName == "item")
                {
                    if (nodeType == XmlNodeType.Element)
                        item = new FeedItem();
                    else if (nodeType == XmlNodeType.EndElement)
                        if (item != null)
                        {
                            items.Add(item);
                            item = null;
                        }

                    continue;
                }

                if (nodeType != XmlNodeType.Element)
                    continue;

                if (nodeName.StartsWith("twitter:"))
                    continue;

                if (item == null)
                    continue;

                string nodeValue;
                
                try
                {
                    reader.MoveToContent();
                    nodeValue = reader.ReadElementContentAsString();
                }
                catch (Exception)
                {
                    continue;
                }

                // we just moved internal pointer
                pointerMoved = true;

                if (nodeName == "title")
                    item.Title = nodeValue;
                else if (nodeName == "description")
                    item.Description = Regex.Replace(nodeValue, @"<(.|\n)*?>", string.Empty);
                else if (nodeName == "feedburner:origLink")
                    item.Link = nodeValue;
                else if (nodeName == "link" && item.Link==null)
                    item.Link = nodeValue;
                else if (nodeName == "pubDate")
                {
                    if (!string.IsNullOrEmpty(nodeValue))
                        item.PublishDate = DateTime.Parse(nodeValue);
                }
                else if (nodeName == "category")
                    item.Categories.Add(nodeValue);
            }

            if (ItemsReceived != null)
                ItemsReceived(this, items,_control);
        }
    }

}
